
import java.io.IOException;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.Sprite;
import javax.microedition.lcdui.game.TiledLayer;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Binh
 */
public final class SunnetGameCanvas extends GameCanvas implements Runnable {
    public  int stage;
    public  int prevStage;
    public volatile boolean isPlay;
    private boolean pause;
    public SunnetMIDlet midlet;
    private Thread t;
    private LayerManager mLayerManager;
    private Font fontLarge, fontSmall, fontMedium, fontText;
    private int width, height;
    private long start, end, time_gc;
    public boolean nextScence;
    private boolean _nextMap;
    public boolean isnmap;
    private int percent;
    public int rh;
    public boolean gameOver;
    //------------------------------------------
    //Dan truyen
    private boolean truyen;
    String[] danchuyen = {"Họ là hai người hạnh phúc nhất tôi từng thấy...", "Nếu như không xảy ra chuyện đó.\n-cô ấy mất rồi. L",
                          "-Một vụ cướp. tai nạn xảy ra. Và cảnh sát thì nghi ngờ mọi chuyện là do tôi dàn dựng lên.Tôi ko thể để bị bắt như thế.",
                          "Mùa đông New York chưa bao giờ lạnh lẽo như vậy.", "6 tháng sau... \n-tôi sắp chết rồi L.",
                          "-anh đùa tôi à?\n-không. Thật đấy. L, khi tôi chết...", "...Hãy tới nhà tôi. Tìm và đọc nhật kí của tôi.\nVà tôi đã tìm thấy giấc mơ của anh ấy.",
                          "Một cỗ máy.\nThứ có thể quay ngược thời gian", "Thứ có thể đưa hạnh phúc trở lại.", "Chỉ thiếu một chi tiết nữa thôi.\nTôi phải giúp anh ấy...\nVì tôi cũng yêu cô ấy.",
                          "Newyork, góc phố 75 và 22.\nkhu phố hỗn loạn...",
                          "Jim Baruva, ông trùm băng đảng xã hội đen lớn nhất thành phố. Đồng thời cũng là chủ tịch đội bóng hockey newyork.\nHắn là chủ của cả khu phố này.\nThứ tôi cần là chiếc cúp vô địch của đội hockey."
                          };
    private int index = 0;
    private Image img;
    //-------------------------------------------
    private Image tuidoIMG;
    private Image khungIMG;
    private TiledLayer thanhduoi, thanhtren, khungnc;
    private Image matnvIMG;
    private Sprite matnv;
    private Image icontuiIMG;
    private Image iconsetIMG;
    private Image mrLIMG;
    private Sprite mrL;
    private Image itemIMG;
    private Sprite item;
    private Image hieuungIMG;
    private Image nenIMG;
    private Image bandoIMG;
    private Image muitenIMG;
    private Image mnIMG;
    private Image nvIMG;
    private Image ctIMG;
    private Image bdIMG;
    private Image tdIMG;
    private Image khungbdIMG;
    private Sprite khungbd;
    public  boolean key4, key6, key2, key8;
    public  boolean press6, press4, press2, press8;
    public  boolean _keyReleased;
    public int prevKey;
    private boolean tuido;
    private boolean bando;
    private boolean ismenuLeft;
    public  int[][] tuidoArray = new int[6][7];
    public boolean[] useItem = new boolean[20];
    public boolean[] updateToBag = new boolean[20];
    private int[][] mrSeq = {{0, 1, 2, 3, 4, 5, 6, 7},
                             {8, 9, 10, 11, 12, 13, 14, 15},
                             {16, 17, 18, 19, 20, 21, 22, 23},
                             {24, 25, 26, 27, 28, 29, 30, 31},
                             {32, 33, 34, 35, 36, 37}
                            };
    private int seqIndex;    
    private TownMap townmap;
    private StockMap stockmap;
    private BarMap barmap;
    private WCMap wcmap;
    private int br, bc;
    private int menuIndex = 0;
    private byte[] textT;
    private int updown;
    private boolean isDrawing;
    private int endTextID;
    private String talk = "Bạn cần váy và tóc giả để vào được quán bar.";
    private String talkover = "Rất tiếc!!Bạn đã chết khi chưa hoàn thành nhiệm vụ";
    private boolean delay;
    byte[] text;
    int choiceItem;
    private int gameCount;
    //Quy uoc: 1 - gay; 2 - son; 3 - kinh; 4 - vay; 5 - that lung; 6 - toc; 7 - nuochoa; 8 - book; 9 - key; 10: paper; 11: ncham
    // 12 - tap ho so; 13 - bom
    public SunnetGameCanvas(SunnetMIDlet midlet) {
        super(false);
        this.midlet = midlet;
        this.setFullScreenMode(true);
        fontLarge = Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_BOLD, Font.SIZE_LARGE);
        fontSmall = Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_PLAIN, Font.SIZE_SMALL);
        fontMedium = Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_PLAIN, Font.SIZE_MEDIUM);
        width = getWidth();
        height = getHeight();
        rh = 0; seqIndex = 0; percent = 0;
    }
    public Sprite getMrL(){
        if(mrL != null)
            return this.mrL;
        return  null;      
    }
    public Sprite getItem(){
        if(item != null)
            return this.item;
        return null;
    }
    public LayerManager getLayerManager(){
        if(mLayerManager != null)
            return this.mLayerManager;
        return null;
    }
    public Image getHieungIMG(){
        if(hieuungIMG != null)
            return this.hieuungIMG;
        return null;
    }
    public TiledLayer getKhungThoai(){
        if(khungnc != null)
            return this.khungnc;
        return null;
    }
    public Sprite getMatNV(){
        if(matnv != null)
            return this.matnv;
        return null;
    }
    public void loadStage(int stage){
        if(mLayerManager == null)
            mLayerManager = new LayerManager();
        try{
            if(mrLIMG == null){
                if(stage!=3)
                    mrLIMG = Image.createImage("/alex.png");
                else{
                    mrLIMG = Image.createImage("/hoatrang.png");
                }
                mrL = new Sprite(mrLIMG, 16, 32);
                mrL.setFrameSequence(mrSeq[seqIndex]);
                
            }
            if(matnv == null){
                matnvIMG = Image.createImage("/matnv.png");
                matnv = new Sprite(matnvIMG, 50, 50);
                matnv.setFrameSequence(new int[]{0, 1, 2, 3, 4});
            }
            if(itemIMG == null){
                itemIMG = Image.createImage("/item.png");
                item = new Sprite(itemIMG, 20, 20);
            }
            if(hieuungIMG == null){
                hieuungIMG =  Image.createImage("/hieuung.png");
            }
            if(khungIMG == null){
                khungIMG = Image.createImage("/khung.png");
                thanhduoi = new TiledLayer(24, 3, khungIMG, 10, 10);
                int[][] tiles = {
                    { 1, 2, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2, 3 },
                    { 4, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 5 },
                    { 6, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 8 }
                };
            
                for (int row = 0; row < 3; row++) {
                    for (int col = 0; col < 24; col++) {
                        thanhduoi.setCell(col, row, tiles[row][col]);
                    }
                }
                thanhtren = new TiledLayer(24, 5, khungIMG, 10, 10);
                tiles = new int[][] {
                    { 1, 2, 2, 2, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3 },
                    { 4, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5 },
                    { 4, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5 },
                    { 4, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5 },
                    { 6, 7, 7, 7, 8, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8 }
                };

                for (int row = 0; row < 5; row++) {
                    for (int col = 0; col < 24; col++) {
                        thanhtren.setCell(col, row, tiles[row][col]);
                    }
                }
                khungnc = new TiledLayer(20, 6, khungIMG, 10, 10);
                tiles = new int[][]{
                    { 1, 2, 2, 2, 3, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3 },
                    { 4, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5 },
                    { 4, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5 },
                    { 4, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5 },
                    { 4, 0, 0, 0, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5 },
                    { 6, 7, 7, 7, 8, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8 }
                };
                for (int row = 0; row < 6; row++) {
                    for (int col = 0; col < 20; col++) {
                        khungnc.setCell(col, row, tiles[row][col]);
                    }
                }
            }
            if(iconsetIMG == null){
                iconsetIMG = Image.createImage("/iconsetting.png");
            }
            if(icontuiIMG == null){
                icontuiIMG = Image.createImage("/icontuido.png");
            }
            if(tuidoIMG == null){
                tuidoIMG = Image.createImage("/tuido.png");
            }
            if(nenIMG == null){
                nenIMG = Image.createImage("/nen.png");
            }
            if(nvIMG == null){
                nvIMG = Image.createImage("/nv.png");
            }
            if(ctIMG == null){
                ctIMG = Image.createImage("/ct.png");
            }
            if(bdIMG == null){
                bdIMG = Image.createImage("/bd.png");
            }
            if(tdIMG == null){
                tdIMG = Image.createImage("/td.png");
            }
            if(mnIMG == null){
                mnIMG = Image.createImage("/mn.png");
            }
            if(muitenIMG == null){
                muitenIMG = Image.createImage("/muiten.png");
            }
            if(bandoIMG == null){
                bandoIMG = Image.createImage("/bando.png");
            }
            if(khungbdIMG == null){
                khungbdIMG = Image.createImage("/khungbando.png");
                khungbd = new Sprite(khungbdIMG, 122, 89);
                khungbd.setFrameSequence(new int[]{0, 1, 2, 3});
            }

        }catch(Exception e){e.printStackTrace();}

        if(stage == 1){
            /*
            if(prevStage == 0)
                nextScence = false;
            else
                nextScence = true;
             *
             */
            nextScence = true;
            townmap = new TownMap();
            townmap.loadMap(this);

        }
        if(stage == 2){
            nextScence = true;
            stockmap = new StockMap();
            stockmap.loadMap(this);    
        }
        if(stage == 3){
            nextScence = true;
            barmap = new BarMap();
            barmap.loadmap(this);
        }
        if(stage == 4){
            nextScence = true;
            wcmap = new WCMap();
            wcmap.loadMap(this);
        }
    }
    public void newGame() {       
        stage = 4;
        loadStage(stage);
        //truyen = true;
    }
    public void continueGame() {
        
    }
    public void start() {
        isPlay = true;
        t = new Thread(this);
        t.start();
    }
    public void menuLeft(Graphics g){
       g.setColor(0x000000);
       g.fillRect(0, 0, width, height);
       g.drawImage(nenIMG, 5, 80, 0);
       g.drawImage(mnIMG, 70 , 140, 0);

       if(menuIndex == 0)
           g.drawImage(tdIMG, 90, 155, 0);
       else
           g.drawImage(tdIMG, 90, 160, 0);
       if(menuIndex == 1)
           g.drawImage(bdIMG, 90, 175, 0);
       else
           g.drawImage(bdIMG, 90, 180, 0);
       if(menuIndex == 2)
           g.drawImage(nvIMG, 90, 195, 0);
       else
           g.drawImage(nvIMG, 90, 200, 0);
       if(menuIndex == 3)
           g.drawImage(ctIMG, 90, 215, 0);
       else
           g.drawImage(ctIMG, 90, 220, 0);
       g.drawImage(muitenIMG, 70, 160 + menuIndex * 20, 0);
    }
    public void drawBando(Graphics g){
        //System.out.println("updown: " + updown);
        g.drawImage(bandoIMG, 10, 70, 0);
        khungbd.setFrame(0);
        khungbd.setPosition(98, 133);
        khungbd.paint(g);
        khungbd.setFrame(3);
        khungbd.setPosition(102, 91 - updown);
        khungbd.paint(g);
        if(updown == 10)
            updown = -5;
    }
    public boolean searchItem(int itemID){
        for(int row = 0; row < 6; row ++){
            for (int col = 0; col < 7; col ++){
                if(tuidoArray[row][col] == itemID){
                    return true;
                }
            }
        }
        return false;
    }
    public void drawTuido(Graphics g){
        g.setColor(0x000000);
        g.fillRect(0, 0, width, height);
        textT = new byte[6];
        Designer.toBytesIndex("Túi đồ" , textT);
        Designer.drawString(g,textT, 0, 6, Designer.FONT_TEXT, 1, width/2 - 10 , 10);
        textT = new byte[5];
        Designer.toBytesIndex("Thoát", textT);
        Designer.drawString(g,textT, 0, 5, Designer.FONT_TEXT, 1, width - 35 , height - 15);
        g.setColor(255, 0, 0);
        for(int row = 0; row < 6; row ++){
            for(int col = 0; col < 7; col ++){
                g.drawImage(tuidoIMG, 35 + col * 25 , 80 + row * 25, 0);
                //g.drawRect(width/2 - 60 + col * 20, 40 + row * 20, 20, 20);
                if(tuidoArray[row][col] == 2){
                    item.setFrame(3);
                    item.setPosition(37 + col * 25, 80 + row * 25);
                    item.paint(g);
                }
                if(tuidoArray[row][col] == 3){
                    item.setFrame(2);
                    item.setPosition(37 + col * 25, 80 + row * 25);
                    item.paint(g);
                }
                if(!useItem[4]){
                    if(tuidoArray[row][col] == 4){
                        item.setFrame(0);
                        item.setPosition(37 + col * 25, 80 + row * 25);
                        item.paint(g);
                    }
                }
                if(tuidoArray[row][col] == 5){
                    item.setFrame(1);
                    item.setPosition(37 + col * 25, 80 + row * 25);
                    item.paint(g);
                }
                if(!useItem[6]){
                    if(tuidoArray[row][col] == 6){
                        item.setFrame(5);
                        item.setPosition(37 + col * 25, 80 + row * 25);
                        item.paint(g);
                    }
                }
                if(tuidoArray[row][col] == 7){
                    item.setFrame(6);
                    item.setPosition(37 + col * 25, 80 + row * 25);
                    item.paint(g);
                }
                if(tuidoArray[row][col] == 8){
                    item.setFrame(13);
                    item.setPosition(37 + col * 25, 80 + row * 25);
                    item.paint(g);
                }
                if(!useItem[9]){
                    if(tuidoArray[row][col] == 9){
                        item.setFrame(14);
                        item.setPosition(37 + col * 25, 80 + row * 25);
                        item.paint(g);
                    }
                }
                if(tuidoArray[row][col] == 10){
                    item.setFrame(18);
                    item.setPosition(37 + col * 25, 80 + row * 25);
                    item.paint(g);
                }
                if(!useItem[11]){
                    if(tuidoArray[row][col] == 11){
                        item.setFrame(7);
                        item.setPosition(37 + col * 25, 80 + row * 25);
                        item.paint(g);
                    }
                }
                if(tuidoArray[row][col] == 12){
                    item.setFrame(17);
                    item.setPosition(37 + col * 25, 80 + row * 25);
                    item.paint(g);
                }
                if(!useItem[13]){
                    if(tuidoArray[row][col] == 13){
                        item.setFrame(19);
                        item.setPosition(37 + col * 25, 80 + row * 25);
                        item.paint(g);
                    }
                }
            }
        }
        g.setColor(0, 255, 0);
        g.drawRect(35 + bc * 25 - 2 , 80 + br * 25 - 2, 30, 30);
        System.gc();
    }
    public void updateToTuido(int type){
        for(int row = 0 ; row < 6; row ++){
            for(int col = 0; col < 6; col++){
                if(tuidoArray[row][col] == 0){
                    tuidoArray[row][col] = type;
                    updateToBag[type] = true;
                    break;
                }
            }
            if(updateToBag[type])
                break;
        }
    }
    public void goNextMap(Graphics g){
        if(stage == 1){
            if((mrL.getY() == 7 * 16 + 8 && mrL.getX() >= 2 * 16 + 8 && mrL.getX() <= 4 * 16 + 8) && !_nextMap){
                if(press2 || key2){
                    _nextMap  = true;
                    townmap.freeMemory();
                    townmap = null;
                    mLayerManager = null;
                    prevStage = 1;
                    stage = 2;
                    loadStage(2);                  
                }
            }
            if(mrL.getX() == 21 * 16 + 8 && mrL.getY() > 20 * 16 + 8 && mrL.getY() < 23 * 16 - 8 ){
                if(key4 || press4){
                    delay = true;                  
                }
                if(useItem[4] && useItem[6]){
                    _nextMap  = true;
                    townmap.freeMemory();
                    townmap = null;
                    mrLIMG = null; // null foe hoa trang
                    mrL = null;
                    mLayerManager = null;
                    prevStage = 3;
                    stage = 3;
                    loadStage(3);
                }
            }
        }
        if(stage == 2){
            if(stockmap.openDoor){
                if(mrL.getY() == 8 * 16 && mrL.getX() > 21 * 16 + 8 && mrL.getX() < 25 * 16 - 8){
                    if(press2 || key2){
                        _nextMap = true;
                        stockmap.freeMemory();
                        stockmap = null;
                        mLayerManager = null;
                        prevStage = 2;
                        stage = 1;
                        loadStage(1);
                        
                    }
                }
            }
        }
        if(stage == 3){
            if((mrL.getY() == 16 * 16 + 8 && mrL.getX() >= 23 * 16  && mrL.getX() <= 25 * 16) && isnmap){
                if(press2 || key2){
                    _nextMap  = true;
                    barmap.freeMemory();
                    barmap = null;
                    mLayerManager = null;
                    prevStage = 3;
                    stage = 4;
                    loadStage(4);
                    //System.out.println("den day");
                }
            }
        }
    }
    public void run() {
        Graphics g = getGraphics();
        int timeStep = 80;
        while (isPlay) {
            start = System.currentTimeMillis();
            if(bando){
                updown = updown + 5;
            }
            if(stage == 1){
                if(townmap.startAccident){                   
                    if(rh < height / 4 - 20)
                        rh = rh + 4;
                    else{
                        if(!townmap.isAccident)
                            townmap.getAccident(this);
                        if(townmap.timeFire > - 1){
                            townmap.timeFire += timeStep;
                            if(!townmap.fum_ap)
                                townmap.timeFumes+= timeStep;
                            else{
                                townmap.nextFrame ++;
                            }
                        }
                    }
                    
                }
                else{
                    if(!townmap.fum_ap)
                        townmap.timeFumes+=timeStep;
                    else{
                        townmap.nextFrame ++;
                    }
                }

            }
            if(stage == 2){
                if(stockmap.open || useItem[0] || useItem[8] || stockmap.drawOutputText || useItem[10])
                    stockmap.nextFrame ++;  
            }

            if(nextScence){
                rh = rh + 8;
                if(rh >=height/2){
                    nextScence = false;
                    rh = 0;
                }
            }
            if(_nextMap){
                percent = percent + 2;
                if(percent == 100){
                    _nextMap = false;
                    nextScence = true;
                    percent = 0;
                }
            }
            //actionMove();
            render(g);
            actionMove();
            end = System.currentTimeMillis();
            int duration = (int) (end - start);
            if (duration < timeStep) {
                try {
                    Thread.sleep(timeStep - duration);
                } catch (InterruptedException ie) {
                    stop();
                }
            }
            time_gc = time_gc + timeStep;
            if (time_gc >= 5000) {
                Runtime.getRuntime().gc();
                time_gc = 0;
            }
        }
    }
    protected void keyPressed(int keyCode) {
        int instantkeyCode = KeyCodeAdapter.getInstance().adoptKeyCode(keyCode);
        switch (instantkeyCode) {
            case KeyCodeAdapter.SOFT_KEY_LEFT:
                ismenuLeft = !ismenuLeft;
                nextScence = true;
                //Set cac meuu item ve false;
                tuido = false;
                bando = false;
                return;
            case KeyCodeAdapter.SOFT_KEY_RIGHT:
                if(truyen){
                    if(img!= null)
                        img = null;
                    stage = 1;
                    loadStage(1);
                    truyen = false;
                    isDrawing = false;
                }
                if(stage ==1){
                    if(townmap.istalk){
                        townmap.talking = true;
                    }
                }
                if(stage == 2){
                    if(stockmap.boardApp){
                        stockmap.boardApp = false;
                        stockmap.textForBoard = false;
                        nextScence = true;
                        prevKey = 0;
                        stockmap.nextFrame = 0;
                        stockmap.drawOutputText = false;
                        stockmap.stringCp = "";
                    }
                }
                return;
            case KeyCodeAdapter.CENTER_KEY:
            case KeyCodeAdapter.KEY_5:
                if(truyen){
                    if(endTextID == danchuyen[index].length()){
                        img = null;
                        isDrawing = false;
                        if(index == 11){
                            stage = 1;
                            loadStage(stage);
                            truyen = false;
                            isDrawing = false;
                        }
                        if(index < 11)
                            index ++;
                    }
                    if(endTextID < danchuyen[index].length())
                        endTextID = danchuyen[index].length();
                }
                if(stage == 1){
                    if(tuido){
                        if(tuidoArray[br][bc] == 4){
                            useItem[4] = true;
                            choiceItem ++;
                        }
                        if(tuidoArray[br][bc] == 6){                            
                            useItem[6] = true;
                            choiceItem ++;
                        }
                        if(choiceItem == 2){
                            tuido = false;
                        }
                    }
                    if(townmap.talking){
                        
                        if(prevStage == 0){
                            if(townmap.talkindex < 4){
                                townmap.talkindex ++;
                                townmap.nextTalk = true;
                            }
                            if(townmap.talkindex == 5){
                                townmap.endtalk = true;
                                townmap.talking = false;
                            }
                        }
                        
                        else{
                            if(townmap.talkindex <= 7){
                                townmap.talkindex ++;
                                townmap.nextTalk = true;
                            }
                            if(townmap.talkindex == 8){
                                townmap.talking = false;
                                townmap.talkindex = 0;
                                townmap.nextTalk = false;
                                townmap.endtalk = true;
                            }
                        }
                    }
                }
                if(stage == 2){
                    if(tuido){                    
                        if(tuidoArray[br][bc] == 8){
                            tuido = false;
                            useItem[8] = true;
                        }
                        if(tuidoArray[br][bc] == 9 && stockmap.useKey){
                            useItem[9] = true;
                            tuido = false;
                        }
                        if(tuidoArray[br][bc] == 10){
                            tuido = false;
                            useItem[10] = true;
                        }
                        if(tuidoArray[br][bc] == 11 && stockmap.useNC){
                            useItem[11] = true;
                            tuido = false;
                        }
                    }
                    else if(stockmap.boardApp){
                        if(!stockmap.isCorrect){
                            if(stockmap.char_row != 3 || (stockmap.char_col != 1 && stockmap.char_col!=0)){
                                stockmap.paintCharacter[stockmap.char_row][stockmap.char_col] = true;
                                stockmap.stringCp = stockmap.stringCp + stockmap.character[stockmap.char_row][stockmap.char_col];
                                stockmap.drawOutputText = false;
                                stockmap.nextFrame = 0;
                            }
                            if(stockmap.char_row == 3 && stockmap.char_col == 1){
                                for(int i = 0; i < 4; i++)
                                    for(int j =0; j < 9; j++){
                                        if(stockmap.paintCharacter[i][j])
                                            stockmap.paintCharacter[i][j] = false;
                                    }

                                stockmap.stringCp = "";
                                stockmap.output = "ENTER KEY CODE";
                                stockmap.drawOutputText = true;
                            }
                            if(stockmap.char_row == 3 && stockmap.char_col == 0){
                                if(stockmap.stringCp.equals("KFQ")){
                                    stockmap.output = "CORRECT!";
                                    stockmap.isCorrect = true;
                                    stockmap.open = true;
                                }
                                else
                                    stockmap.output = "NOT CORRECT";
                                stockmap.stringCp = "";
                                stockmap.drawOutputText = true;
                            }
                        }
                    }
                    else{
                        if(stockmap.showBook){
                            stockmap.getBook().setFrame(0);
                            stockmap.showBook = false;
                            useItem[8] = false;
                            stockmap.nextString = false;
                        }
                        if(stockmap.showPaper){
                            stockmap.getPaper().setFrame(0);
                            stockmap.showPaper = false;
                            useItem[10] = false;
                        }    
                    }
                }
                if(stage == 3){
                    if(tuido){
                        if(tuidoArray[br][bc] == 13 && barmap.useBom){
                            tuido = false;
                            useItem[13] = true;
                        }
                    }
                    if(barmap.talking){
                        if(barmap.talkIndex <= 3){
                            if(barmap.endTextID < barmap.talk[barmap.talkIndex].length()){
                                barmap.endTextID = barmap.talk[barmap.talkIndex].length();
                            }
                            else{
                                barmap.talkIndex ++;
                                barmap.isDrawing = false;
                            }
                        }
                        if(barmap.talkIndex == 4){
                            barmap.talking = false;
                            barmap.isDrawing = false;
                            barmap.iswar = true;
                        }
                    }
                }
                if(ismenuLeft){
                    if(menuIndex == 0){
                        tuido = true;
                        nextScence = true;
                        bando = false;
                    }
                    if(menuIndex == 1){
                        updown = 0;
                        bando = true;
                        nextScence = true;
                        tuido = false;
                    }
                    ismenuLeft = false;
                }
                return;
            case KeyCodeAdapter.RIGHT_KEY:
            case KeyCodeAdapter.KEY_6:
                if(tuido){
                    if(bc < 6)
                        bc ++;
                    else bc = 0;
                }
                if(stage == 1){
                    if(!gameOver && !tuido && !townmap.startAccident && !townmap.talking){
                        if(!_keyReleased){
                            _keyReleased = true;
                            key6 = true;
                            press6 = true;
                            seqIndex = 2;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                if(stage == 2){
                    if(!gameOver && !stockmap.delay && !stockmap.boardApp && !tuido){
                        if(!_keyReleased){
                            _keyReleased = true;
                            key6 = true;
                            press6 = true;
                            seqIndex = 2;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                    if(stockmap.boardApp){
                        if(stockmap.char_row <=1){
                            if(stockmap.char_col < 8)
                                stockmap.char_col ++;
                            else
                                stockmap.char_col = 0;
                        }
                        else if(stockmap.char_row == 2){
                            if(stockmap.char_col < 7)
                                stockmap.char_col ++;
                            else
                                stockmap.char_col = 0;
                        }
                        else if(stockmap.char_row == 3){
                            if(stockmap.char_col < 1)
                                stockmap.char_col ++;
                            else
                                stockmap.char_col = 0;
                        }
                    }
                }
                if(stage == 3){
                    if(!gameOver && !tuido){
                        if(!_keyReleased){
                            _keyReleased = true;
                            key6 = true;
                            press6 = true;
                            seqIndex = 2;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                if(stage == 4){
                    if(!gameOver && !tuido){
                        if(!_keyReleased){
                            _keyReleased = true;
                            key6 = true;
                            press6 = true;
                            seqIndex = 2;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                prevKey = 6;
                
                return;
            case KeyCodeAdapter.LEFT_KEY:
            case KeyCodeAdapter.KEY_4:
                if(tuido){
                    if(bc > 0)
                        bc --;
                    else
                        bc = 6;
                }
                if(stage == 1){
                    if(!gameOver && !tuido && !townmap.startAccident && !townmap.talking){
                        if(!_keyReleased){
                            key4 = true;
                            press4 = true;
                            _keyReleased = true;
                            seqIndex = 3;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                if(stage == 2){
                    if(!gameOver && !stockmap.delay && !stockmap.boardApp && !tuido){
                        if(!_keyReleased){
                            _keyReleased = true;
                            key4 = true;
                            press4 = true;
                            seqIndex = 3;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                    if(stockmap.boardApp){
                        if(stockmap.char_row <=1){
                            if(stockmap.char_col > 0)
                                stockmap.char_col --;
                            else
                                stockmap.char_col = 8;
                        }
                        else if(stockmap.char_row == 2){
                            if(stockmap.char_col > 0)
                                stockmap.char_col --;
                            else
                                stockmap.char_col = 7;
                        }
                        else if(stockmap.char_row == 3){
                            if(stockmap.char_col > 0)
                                stockmap.char_col --;
                            else
                                stockmap.char_col = 1;
                        }
                    }
                }
                if(stage == 3){
                    if(!gameOver && !tuido){
                        if(!_keyReleased){
                            key4 = true;
                            press4 = true;
                            seqIndex = 3;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                if(stage == 4){
                    if(!gameOver && !tuido){
                        if(!_keyReleased){
                            key4 = true;
                            press4 = true;
                            seqIndex = 3;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                prevKey = 4;
                return;
            case KeyCodeAdapter.UP_KEY:
            case KeyCodeAdapter.KEY_2:

                if(ismenuLeft){
                   if(menuIndex > 0)
                       menuIndex --;
                   else
                       menuIndex = 3;
                    
                }
                if(tuido){
                    if(br > 0)
                        br --;
                    else
                        br = 5;
                }
                if(stage == 1){
                    if(!gameOver && !tuido && !townmap.startAccident && !townmap.talking){
                        if(!_keyReleased){
                            _keyReleased = true;
                            key2 = true;
                            press2 = true;
                            seqIndex = 0;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                if(stage == 2){
                    if(!gameOver && !stockmap.delay && !stockmap.boardApp && !tuido){
                        if(!_keyReleased){
                            key2 = true;
                            press2 = true;
                            seqIndex = 0;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                    if(stockmap.boardApp){
                        if(stockmap.char_row > 0)
                            stockmap.char_row --;
                        else
                            stockmap.char_row = 3;
                        if(stockmap.char_row == 2 && stockmap.char_col > 7)
                            stockmap.char_col = 7;
                        if(stockmap.char_row == 3 && stockmap.char_col > 1)
                            stockmap.char_col = 1;
                    }
                }
                if(stage == 3){
                    if(!gameOver && !tuido){
                        if(!_keyReleased){
                            key2 = true;
                            press2 = true;
                            seqIndex = 0;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                if(stage == 4){
                    if(!gameOver && !tuido){
                        if(!_keyReleased){
                            key2 = true;
                            press2 = true;
                            seqIndex = 0;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                prevKey = 2;
                return;
            case KeyCodeAdapter.DOWN_KEY:
            case KeyCodeAdapter.KEY_8:
                if(ismenuLeft){
                    if(menuIndex < 3)
                        menuIndex ++;
                    else
                        menuIndex = 0;
                }
                if(tuido){
                    if(br < 5)
                        br ++;
                    else
                        br = 0;
                }
                if(stage == 1){
                    if(!gameOver && !tuido && !townmap.startAccident && !townmap.talking){
                        if(!_keyReleased){
                            _keyReleased = true;
                            key8 = true;
                            press8 = true;
                            seqIndex = 1;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                if(stage == 2){
                    if(!gameOver && !stockmap.delay && !stockmap.boardApp && !tuido){
                        if(!_keyReleased){
                            _keyReleased = true;
                            key8 = true;
                            press8 = true;
                            seqIndex = 1;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                    if(stockmap.boardApp){
                        if(stockmap.char_row < 3)
                            stockmap.char_row ++;
                        else
                            stockmap.char_row = 0;
                        if(stockmap.char_row == 2 && stockmap.char_col > 7)
                            stockmap.char_col = 7;
                        if(stockmap.char_row == 3 && stockmap.char_col > 1)
                            stockmap.char_col = 1;
                    }
                }
                if(stage == 3){
                    if(!gameOver && !tuido){
                        if(!_keyReleased){
                            key8 = true;
                            press8 = true;
                            seqIndex = 1;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                if(stage == 4){
                    if(!gameOver && !tuido){
                        if(!_keyReleased){
                            key8 = true;
                            press8 = true;
                            seqIndex = 1;
                            mrL.setFrameSequence(mrSeq[seqIndex]);
                            mrL.setFrame(0);
                        }
                    }
                }
                prevKey = 8;
                return;
        }
    }
    protected void keyReleased(int keyCode) {
        int instantkeyCode = KeyCodeAdapter.getInstance().adoptKeyCode(keyCode);
        switch (instantkeyCode) {
            case KeyCodeAdapter.LEFT_KEY:
            case KeyCodeAdapter.KEY_4:
                key4 = false;
                _keyReleased = false;
                return;
            case KeyCodeAdapter.RIGHT_KEY:
            case KeyCodeAdapter.KEY_6:
                key6 = false;
                _keyReleased = false;
                return;
            case KeyCodeAdapter.UP_KEY:
            case KeyCodeAdapter.KEY_2:
                key2 = false;
                _keyReleased = false;
                return;
            case KeyCodeAdapter.DOWN_KEY:
            case KeyCodeAdapter.KEY_8:
                 key8 = false;
                 _keyReleased = false;
                 return;
        }
    }
    public void actionMove(){
        if(stage == 1){
            if(townmap.isLoaded)
                townmap.getCollides(this);
        }
        if(stage == 2){
            stockmap.getColides(this);
        }
        if(stage == 3){
            barmap.getColides(this);
        }
        if(stage == 4){
            wcmap.getColides(this);
        }
        if(!key6 && press6){
            if(mrL.getFrame()!=0){
                 mrL.nextFrame();
                 mrL.move(4, 0);
            }
            else
                press6 = false;
        }
        if(!key4 && press4){
             if(mrL.getFrame()!=0){
                 mrL.nextFrame();
                 mrL.move(-4, 0);
             }
             else
                 press4 = false;
        }
        if(!key2 && press2){
             if(mrL.getFrame()!=0){
                 mrL.nextFrame();
                 mrL.move(0, -4);
             }
             else
                 press2 = false;
        }
        if(!key8 && press8){
             if(mrL.getFrame()!=0){
                 mrL.nextFrame();
                 mrL.move(0, 4);
             }
             else
                 press8 = false;
        }
        if(key6) {
             mrL.nextFrame();
             mrL.move(4, 0);
        }
        if(key4) {
             mrL.nextFrame();
             mrL.move(-4, 0);
        }
        if(key8){
             mrL.nextFrame();
             mrL.move(0, 4);
        }
        if(key2){
              mrL.nextFrame();
              mrL.move(0, -4);
        }
    }
    public void drawCotTruyen(Graphics g){
        g.setColor(0x000000);
        g.fillRect(0, 0, width, height);
        if(img == null){
            try {
                if(index != 4 && index != 7 && index != 9 && index != 10){
                    //System.out.println("/truyen/" + (index + 1) + ".png");
                    if(index < 4)
                        img = Image.createImage("/truyen/" + (index + 1) + ".png");
                    if(index == 5 || index == 6)
                        img = Image.createImage("/truyen/" + index  + ".png");
                    if(index == 8)
                        img = Image.createImage("/truyen/1.png");
                    if(index == 11)
                         img = Image.createImage("/truyen/7.png");
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        if(index != 4 && index != 7 && index != 9 && index != 10)
            g.drawImage(img, (width - img.getWidth()) / 2, 20, 0);
        if(!isDrawing){
             text = new byte[danchuyen[index].length()];
             Designer.toBytesIndex(danchuyen[index] , text);
             isDrawing = true;
             endTextID = 0;
        }
        else{
            if(endTextID < danchuyen[index].length())
                endTextID ++;          
        }
        if(index != 4 && index != 7 && index != 9 && index != 10)
            Designer.drawString(g, text, 0, endTextID, Designer.FONT_TEXT, Designer.MARGIN_LEFT, false, 0, 10 , 30  + img.getHeight(), width - 20, height - img.getHeight());
        else{
            if(index != 10)
                Designer.drawString(g, text, 0, endTextID, Designer.FONT_TEXT, Designer.MARGIN_LEFT, false, 0, 10 , 30 , width - 20, height - 30);
            else
                Designer.drawString(g, text, 0, endTextID, Designer.FONT_TEXT, Designer.MARGIN_LEFT, false, 0, width / 2 - 30 , height - 50 , width/2 + 30, 50);
        }
    }
    public void render(Graphics g) {
        g.setColor(0x000000);
        g.fillRect(0, 0, width, height);
        System.out.println("mrL.getX:" + mrL.getX() + "mrL.getY:" + mrL.getY());
        if(stage == 1){   
            if(!_nextMap){
                if(!tuido && !bando && townmap.isLoaded)
                    townmap.drawMap(g, this);
            }
            else{
                g.drawImage(nenIMG, 5, 70, 0);
                String pt = new String("Loading : " + percent + "%");
                textT = new byte[pt.length()];
                Designer.toBytesIndex(pt, textT);
                Designer.drawString(g,textT, 0, pt.length(), Designer.FONT_TEXT, 1, width /2 - 30 , height/2 + 30);
            }
            if(delay){
                g.setColor(55, 77, 91);
                g.fillRect(20, height - 90, 200, 60);
                matnv.setFrame(2);
                matnv.setPosition(20, height - 85);
                matnv.paint(g);
                khungnc.setPosition(20, height - 90);
                khungnc.paint(g);
                if(!isDrawing){
                    text = new byte[talk.length()];
                    Designer.toBytesIndex(talk , text);
                    isDrawing = true;
                    endTextID = 0;
                }
                else{
                    if(endTextID < talk.length())
                        endTextID ++;
                    if(endTextID >= talk.length()){
                        isDrawing = false;
                        delay = false;
                    }
                }
                Designer.drawString(g, text, 0, endTextID, Designer.FONT_TEXT, Designer.MARGIN_LEFT, false, 2, 75 , height - 85, 150, 50);
            }
        }
        if(stage == 2){
            if(!_nextMap){
                if(!tuido && !bando){
                    stockmap.drawMap(g, this);
                }
            }
            else{
                g.drawImage(nenIMG, 5, 70, 0);
                String pt = new String("Loading : " + percent + "%");
                textT = new byte[pt.length()];
                Designer.toBytesIndex(pt, textT);
                Designer.drawString(g,textT, 0, pt.length(), Designer.FONT_TEXT, 1, width /2 - 30 , height/2 + 30);
            }
        }
        if(stage == 3){
            if(!_nextMap){
                if(!tuido && !bando)
                    barmap.drawMap(this, g);
            }
            else{
                g.drawImage(nenIMG, 5, 70, 0);
                String pt = new String("Loading : " + percent + "%");
                textT = new byte[pt.length()];
                Designer.toBytesIndex(pt, textT);
                Designer.drawString(g,textT, 0, pt.length(), Designer.FONT_TEXT, 1, width /2 - 30 , height/2 + 30);
            }
        }
        if(stage == 4){
            if(!_nextMap){
                if(!tuido && !bando)
                    wcmap.drawMap(this, g);
            }
            else{
                g.drawImage(nenIMG, 5, 70, 0);
                String pt = new String("Loading : " + percent + "%");
                textT = new byte[pt.length()];
                Designer.toBytesIndex(pt, textT);
                Designer.drawString(g,textT, 0, pt.length(), Designer.FONT_TEXT, 1, width /2 - 30 , height/2 + 30);
            }
        }
        if(gameOver){
            if(mrL.getFrame()!= 2)
                mrL.nextFrame();
            else{
                gameCount ++;
                if(gameCount >= 10){
                    matnv.setFrame(2);
                    matnv.setPosition(20, height - 85);
                    matnv.paint(g);
                    khungnc.setPosition(20, height - 90);
                    khungnc.paint(g);
                    if(!isDrawing){
                        text = new byte[talkover.length()];
                        Designer.toBytesIndex(talkover , text);
                        isDrawing = true;
                        endTextID = 0;
                    }
                    else{
                        if(endTextID < talkover.length())
                            endTextID ++;
                        if(endTextID >= talkover.length()){
                            //Man hinh mau do
                            isDrawing = false;
                            delay = false;
                            exitGame();
                        }
                    }
                    Designer.drawString(g, text, 0, endTextID, Designer.FONT_TEXT, Designer.MARGIN_LEFT, false, 2, 75 , height - 85, 150, 50);
                }
            }
            
        }
        if(!truyen){
            if(ismenuLeft){
                menuLeft(g);
            }
            if(tuido){
                drawTuido(g);
            }
            if(bando){
                drawBando(g);
            }
            // paint thanh duoi
            
            g.setColor(55, 77, 91);
            g.fillRect(5, height - 25, 230, 20);
            thanhduoi.setPosition(0, height - 30);
            thanhduoi.paint(g);
            g.drawImage(icontuiIMG, 10, thanhduoi.getY() + 5, 0);
            g.drawImage(iconsetIMG, width - iconsetIMG.getWidth() - 10, thanhduoi.getY() + 4, 0);
           
            // thanh tren
            g.fillRect(5, 5, 230, 40);
            matnv.setFrame(4);
            matnv.setPosition(5, 0);
            matnv.paint(g);
            thanhtren.setPosition(0, 0);
            thanhtren.paint(g);
            if(barmap!= null){
                if(barmap.isDrawTime){
                    item.setFrame(19);
                    item.setPosition(width - 40, 15);
                    item.paint(g);
                    textT = new byte[2];
                    Designer.toBytesIndex((":" + barmap.tgcount), textT);
                    Designer.drawString(g, textT, 0, 2, Designer.FONT_TEXT,  3, width - 20 , 20);
                }
            }
            //------------- To next map -------------------------//
            goNextMap(g);
        }
        else{
            drawCotTruyen(g);
        }
        if(nextScence){
            g.setColor(0x000000);
            g.fillRect(0, height/2 + rh, width, height/2);
            g.fillRect(0, 0, width, height/2 - rh);
        }
        
        System.gc();
        flushGraphics();
    }
    public void stop() {
        isPlay = false;
        t = null;
    }
    public void exitGame(){
      this.stop();
      //Giai phong bo nho
      /*
       -----------------
       */
      Runtime.getRuntime().gc();
      midlet.showMenu();

  }
}
